@echo off
chcp 65001 >nul
REM Windows AMD64 Client Build Script
REM Used to build Flutter client on Windows systems

setlocal enabledelayedexpansion

echo ================================================================================
echo 🪟 Windows AMD64 Client Build Script
echo ================================================================================
echo.

REM Get script directory
set SCRIPT_DIR=%~dp0
cd /d "%SCRIPT_DIR%"

echo 📋 Checking build environment...
echo.

REM Check Flutter
where flutter >nul 2>nul
if %errorlevel% neq 0 (
    echo ❌ Flutter is not installed or not in PATH
    echo    Please install Flutter first: https://flutter.dev/docs/get-started/install/windows
    pause
    exit /b 1
)

echo ✅ Flutter version:
flutter --version | findstr "Flutter"
echo.

REM Check Go
where go >nul 2>nul
if %errorlevel% neq 0 (
    echo ❌ Go is not installed or not in PATH
    echo    Please install Go first: https://golang.org/dl/
    pause
    exit /b 1
)

for /f "tokens=*" %%i in ('go version') do set GO_VERSION=%%i
echo ✅ Go version: %GO_VERSION%
echo.

REM Check C compiler (required for CGO)
echo 🔍 Checking C compiler (required for CGO)...
set COMPILER_FOUND=0

REM Check for GCC first
where gcc >nul 2>nul
if %errorlevel% equ 0 (
    set COMPILER_FOUND=1
    for /f "tokens=*" %%i in ('where gcc') do set GCC_PATH=%%i
    echo ✅ GCC found at: !GCC_PATH!
) else (
    REM Check for GCC in common locations
    if exist "C:\TDM-GCC-64\bin\gcc.exe" (
        set COMPILER_FOUND=1
        set GCC_PATH=C:\TDM-GCC-64\bin\gcc.exe
        echo ✅ GCC found at: !GCC_PATH!
        echo    Adding C:\TDM-GCC-64\bin to PATH
        set PATH=C:\TDM-GCC-64\bin;%PATH%
    ) else if exist "C:\MinGW\bin\gcc.exe" (
        set COMPILER_FOUND=1
        set GCC_PATH=C:\MinGW\bin\gcc.exe
        echo ✅ GCC found at: !GCC_PATH!
        echo    Adding C:\MinGW\bin to PATH
        set PATH=C:\MinGW\bin;%PATH%
    ) else if exist "C:\msys64\mingw64\bin\gcc.exe" (
        set COMPILER_FOUND=1
        set GCC_PATH=C:\msys64\mingw64\bin\gcc.exe
        echo ✅ GCC found at: !GCC_PATH!
        echo    Adding C:\msys64\mingw64\bin to PATH
        set PATH=C:\msys64\mingw64\bin;%PATH%
    ) else (
        REM Check for Visual Studio C++ compiler (cl.exe)
        where cl.exe >nul 2>nul
        if %errorlevel% equ 0 (
            set COMPILER_FOUND=1
            for /f "tokens=*" %%i in ('where cl.exe') do set CL_PATH=%%i
            echo ✅ Visual Studio C++ compiler ^(cl.exe^) found at: !CL_PATH!
        ) else (
            REM Try to find Visual Studio installation and check for cl.exe there
            set VSWHERE="C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe"
            if exist !VSWHERE! (
                for /f "tokens=*" %%i in ('!VSWHERE! -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -find **\bin\Hostx64\x64\cl.exe 2^>nul') do set CL_PATH=%%i
                if defined CL_PATH (
                    set COMPILER_FOUND=1
                    echo ✅ Visual Studio C++ compiler ^(cl.exe^) found at: !CL_PATH!
                )
            )
        )
    )
)

if "!COMPILER_FOUND!"=="0" (
    echo ⚠️  No C compiler found
    echo    CGO-enabled builds require a C compiler:
    echo    Option 1: Install MinGW-w64 or MSYS2 with GCC
    echo    Option 2: Install Visual Studio with C++ build tools
    echo.
    echo    If you continue without a C compiler, the Go tunnel library compilation will fail.
    echo.
    set /p CONTINUE="Continue anyway? (y/N): "
    if /i not "!CONTINUE!"=="y" (
        exit /b 1
    )
)
echo.

REM Check NuGet
echo 🔍 Checking NuGet...
set NUGET_FOUND=0

REM Check if nuget is in PATH
where nuget >nul 2>nul
if %errorlevel% equ 0 (
    set NUGET_FOUND=1
    for /f "tokens=*" %%i in ('where nuget') do set NUGET_PATH=%%i
    echo ✅ NuGet found at: !NUGET_PATH!
) else (
    REM Check for NuGet in common locations
    if exist "D:\tools\nuget.exe" (
        set NUGET_FOUND=1
        set NUGET_PATH=D:\tools\nuget.exe
        echo ✅ NuGet found at: !NUGET_PATH!
        echo    Adding D:\tools to PATH
        set PATH=D:\tools;%PATH%
    ) else if exist "C:\Program Files (x86)\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\NuGet.exe" (
        set NUGET_FOUND=1
        set NUGET_PATH=C:\Program Files (x86)\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\NuGet.exe
        echo ✅ NuGet found at: !NUGET_PATH!
        echo    Adding C:\Program Files (x86)\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin to PATH
        set PATH=C:\Program Files (x86)\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin;%PATH%
    ) else if exist "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\MSBuild\Current\Bin\NuGet.exe" (
        set NUGET_FOUND=1
        set NUGET_PATH=C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\MSBuild\Current\Bin\NuGet.exe
        echo ✅ NuGet found at: !NUGET_PATH!
        echo    Adding C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\MSBuild\Current\Bin to PATH
        set PATH=C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\MSBuild\Current\Bin;%PATH%
    )
)

if "!NUGET_FOUND!"=="0" (
    echo ⚠️  NuGet not found
    echo    NuGet is required for Flutter Windows builds
    echo    Please install NuGet or ensure it's in your PATH
    echo.
    set /p CONTINUE="Continue anyway? (y/N): "
    if /i not "!CONTINUE!"=="y" (
        exit /b 1
    )
)
echo.

REM Check Visual Studio (MSBuild)
set VS_FOUND=0
where cl.exe >nul 2>nul
if %errorlevel% equ 0 (
    set VS_FOUND=1
    for /f "tokens=*" %%i in ('where cl.exe') do set CL_PATH=%%i
) else (
    REM Try to find Visual Studio installation
    set VSWHERE="C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe"
    if exist !VSWHERE! (
        for /f "tokens=*" %%i in ('!VSWHERE! -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -find **\bin\Hostx64\x64\cl.exe 2^>nul') do set CL_PATH=%%i
        if defined CL_PATH (
            set VS_FOUND=1
        )
    )
)

if "%VS_FOUND%"=="0" (
    echo ⚠️  Warning: Visual Studio C++ compiler not detected
    echo    Flutter Windows build requires Visual Studio 2022 and C++ desktop development tools
    echo    Download: https://visualstudio.microsoft.com/
    echo.
    echo    If already installed, run this script in "x64 Native Tools Command Prompt for VS 2022"
    echo.
    set /p CONTINUE="Continue? (y/N): "
    if /i not "!CONTINUE!"=="y" (
        exit /b 1
    )
) else (
    echo ✅ Visual Studio C++ compiler found at: !CL_PATH!
)
echo.

echo 📟 Current OS: Windows
echo.

REM ============================================================
REM Step 1: Compile Go Tunnel Library (Windows AMD64)
REM ============================================================

echo ================================================================================
echo 🔨 Step 1/3: Compile Go Tunnel Library (Windows AMD64)
echo ================================================================================
echo.

cd go_tunnel

REM Clean Go build cache and temporary files
echo 🗑️  Cleaning Go build cache and temporary files...
go clean -cache 2>nul
del /q *.o *.a *.so *.dll *.dylib 2>nul
echo.

REM Create output directory
set OUTPUT_DIR=..\assets\libs
if not exist "%OUTPUT_DIR%" mkdir "%OUTPUT_DIR%"

set OUTPUT_FILE=%OUTPUT_DIR%\simple_tunnel_windows_amd64.dll

REM Clean old files
if exist "%OUTPUT_FILE%" (
    echo 🗑️  Cleaning old DLL files...
    del /q "%OUTPUT_FILE%"
    del /q "%OUTPUT_FILE:~0,-4%.h" 2>nul
)

echo ✅ Compiling directly on Windows system...
echo.

REM Set environment variables
set GOOS=windows
set GOARCH=amd64
set CGO_ENABLED=1

echo 🔍 Build parameters: GOOS=%GOOS% GOARCH=%GOARCH% CGO_ENABLED=%CGO_ENABLED%
echo.

REM Compile Go DLL - Only include files relevant to Windows platform
echo Compiling Go DLL...
set GO_FILES=connection_pool.go http2_client.go http2_connection_pool.go http_protocol.go interfaces.go tunnel_connection_pool.go tunnel_manager.go

REM Check if all required files exist
for %%f in (%GO_FILES%) do (
    if not exist "%%f" (
        echo ❌ Required file not found: %%f
        cd ..
        pause
        exit /b 1
    )
)

go build -a -buildmode=c-shared -ldflags="-s -w" -o "%OUTPUT_FILE%" %GO_FILES%
if %errorlevel% neq 0 (
    echo.
    echo ❌ Windows DLL compilation failed
    cd ..
    pause
    exit /b 1
)

echo.
echo ✅ Windows DLL compiled successfully!
for %%A in ("%OUTPUT_FILE%") do (
    echo    File: %%~fA
    echo    Size: %%~zA bytes
)
echo.

cd ..

echo.

REM ============================================================
REM Step 2: Flutter Dependencies Installation
REM ============================================================

echo ================================================================================
echo 📦 Step 2/3: Installing Flutter Dependencies
echo ================================================================================
echo.

echo 📥 Getting Flutter dependencies...
flutter pub get
if %errorlevel% neq 0 (
    echo.
    echo ❌ Flutter dependencies installation failed
    pause
    exit /b 1
)

echo.
echo ✅ Dependencies installation completed
echo.

REM ============================================================
REM Step 3: Build Flutter Windows Application
REM ============================================================

echo ================================================================================
echo 🏗️  Step 3/3: Building Flutter Windows Application
echo ================================================================================
echo.

echo 🔨 Starting Windows Release build...
echo.

REM Clean previous builds
if exist "build\windows" (
    echo 🗑️  Cleaning old build files...
    rmdir /s /q "build\windows"
)

REM Build Windows application
echo Building Windows application...
flutter build windows --release
if %errorlevel% neq 0 (
    echo.
    echo ❌ Flutter Windows application build failed
    echo.
    
    echo 💡 Common issues:
    echo    1. Ensure Visual Studio 2022 and C++ desktop development tools are installed
    echo    2. Run this script in "x64 Native Tools Command Prompt for VS 2022"
    echo    3. Run flutter doctor to check environment
    echo    4. NuGet.exe not found - install Visual Studio or NuGet command line tool
    echo.
    pause
    exit /b 1
)

echo.
echo ✅ Flutter Windows application built successfully!
echo.

REM Show output directory
set BUILD_OUTPUT=build\windows\x64\runner\Release
if exist "%BUILD_OUTPUT%" (
    echo 📁 Build output directory:
    echo    %CD%\%BUILD_OUTPUT%
    echo.
    
    REM Show executable file
    if exist "%BUILD_OUTPUT%\internal_net_bridge.exe" (
        for %%A in ("%BUILD_OUTPUT%\internal_net_bridge.exe") do (
            echo 🚀 Executable file:
            echo    internal_net_bridge.exe (%%~zA bytes)
            echo.
        )
    )
    
    REM Check if DLL was copied
    if exist "%BUILD_OUTPUT%\data\flutter_assets\assets\libs\simple_tunnel_windows_amd64.dll" (
        echo ✅ Go Tunnel DLL included in application
    ) else (
        echo ⚠️  Warning: Go Tunnel DLL not found, application may not work properly
    )
    echo.
    
    REM List main files
    echo 📦 Main file list:
    dir /b "%BUILD_OUTPUT%" | findstr /v /i "^d"
    echo.
)

REM ============================================================
REM Build Completion Summary
REM ============================================================

echo ================================================================================
echo 🎉 Windows AMD64 Client Build Completed!
echo ================================================================================
echo.
echo 📍 Output location:
echo    %CD%\%BUILD_OUTPUT%
echo.
echo 📦 Packaging suggestions:
echo    1. Package entire Release directory as ZIP file:
echo       powershell Compress-Archive -Path "%BUILD_OUTPUT%" -DestinationPath internal_net_bridge_windows_amd64.zip
echo.
echo    2. Or use NSIS/Inno Setup to create installer
echo.
echo 🚀 Testing method:
echo    cd %BUILD_OUTPUT%
echo    internal_net_bridge.exe
echo.
echo ⚠️  Notes:
echo    1. Ensure target system has Visual C++ Redistributable installed
echo       Download: https://aka.ms/vs/17/release/vc_redist.x64.exe
echo    2. First run may require administrator privileges
echo    3. Firewall may pop up prompts, network access needs to be allowed
echo.
echo ✨ Done!

pause